//
//  MFWUserInfo.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-7-24.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "MFWUserInfo.h"

static NSString *const kCodingUid = @"id";
static NSString *const kCodingNikcName = @"username";
static NSString *const kCodingLogoUrl = @"header";
static NSString *const kCodingLevel = @"level";
static NSString *const kCodingGender = @"gender";
static NSString *const kCodingUCity = @"location";
static NSString *const kCodingUIntro = @"desc";
static NSString *const kCodingUbgimg = @"m_bg_img";
static NSString *const kCodingUChatNum = @"chatnum";
static NSString *const kCodingEmail = @"email";
static NSString *const kCodingTrueName = @"truename";
static NSString *const kCodingPhone = @"phone";
static NSString *const kCodingSex = @"sex";
static NSString *const kCodingBirthday = @"birthday";
static NSString *const kCodingProfile = @"profile";
static NSString *const kCodingFans = @"fans";
static NSString *const kCodingConcern = @"concern";


@implementation MFWUserInfo

+ (NSString *)cachePathOfMyUserInfo
{
//    return [[NSFileManager defaultManager] pathForPublicFile:@"user.data"];
    return [[NSFileManager defaultManager] pathForLibraryFile:@"user.data"];
}

- (BOOL)updateInfoFromUserJsonData:(MFWJson*)jsonData;
{
    if (jsonData && ![jsonData isKindOfClass:[MFWJson class]])
    {
        return NO;
    }
    
    self.uid = [jsonData stringValueForKey:@"id"];
    self.nickName = [jsonData stringValueForKey:@"username"];
    if ([jsonData hasValueForKey:@"extinfo"])
    {
        MFWJson *extInfo = [jsonData jsonForKey:@"extinfo"];
    self.logoUrl = [extInfo stringValueForKey:@"icon"];
    self.gender = [extInfo intValueForKey:@"gender"];
    self.ucity = [extInfo stringValueForKey:@"location"];
    self.uIntro = [extInfo stringValueForKey:@"signature"];
    self.un_read_chat_count = [extInfo intValueForKey:@"chatnum" defaultValue:0];
    self.m_bg_img = [extInfo stringValueForKey:@"img"];
    }else{
        self.ucity=[jsonData stringValueForKey:@"location"];
        self.gender = [jsonData intValueForKey:@"gender"];
        self.uIntro =[jsonData stringValueForKey:@"signature"];
        self.logoUrl=[jsonData stringValueForKey:@"icon"];
        self.level =[jsonData intValueForKey:@"level"];
        self.un_read_chat_count = [jsonData intValueForKey:@"chatnum" defaultValue:0];
        self.m_bg_img = [jsonData stringValueForKey:@"img"];
        self.phone = [jsonData stringValueForKey:@"phone"];
        self.trueName = [jsonData stringValueForKey:@"truename"];
        self.sex = [jsonData stringValueForKey:@"sex"];
        self.birthday = [jsonData stringValueForKey:@"birthday"];
        self.profile = [jsonData stringValueForKey:@"profile"];
        self.fans = [jsonData stringValueForKey:@"fans"];
        self.concern = [jsonData stringValueForKey:@"attent"];
        self.extra = [jsonData copy];
    }
    dispatch_async(dispatch_get_main_queue(), ^
       {
           [self synchronizeToDisk];
       });
    
    return YES;
}

- (BOOL)synchronizeToDisk;
{
    NSMutableData * data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:self];
    [archiver finishEncoding];
    BOOL result = [data writeToFile:[MFWUserInfo cachePathOfMyUserInfo] atomically:YES];
    
    return result;
}

- (NSString *)description
{
    NSMutableString * rtnString = [NSMutableString string];
    [rtnString appendFormat:@"uid:%@\n",self.uid];
    [rtnString appendFormat:@"name:%@\n",self.nickName];
    [rtnString appendFormat:@"logo:%@\n",self.logoUrl];
    [rtnString appendFormat:@"gender:%d\n",self.gender];
    [rtnString appendFormat:@"ucity:%@\n",self.ucity];
    [rtnString appendFormat:@"uintro:%@\n",self.uIntro];
    [rtnString appendFormat:@"cover:%@\n",self.m_bg_img];

    return rtnString;
}

- (BOOL)clear
{
    NSString* cache_path = [MFWUserInfo cachePathOfMyUserInfo];
    BOOL res = [[NSFileManager defaultManager] removeItemAtPath:cache_path error:nil];
    if (res)
    {
        self.uid = nil;
        self.nickName = nil;
        self.logoUrl = nil;
        self.uIntro = nil;
        self.ucity = nil;
        self.m_bg_img = nil;
        self.email = nil;
        self.level = 0;
        self.un_read_chat_count = 0;
    }
    return res;
}

+ (MFWUserInfo*)loadFromDisk;
{
    /*
     * 6.1.0之前，用户的登录信息保存在了Documents下，用户反馈登录信息会自动消失，
     * 经过排查，可能的原因是，缓存在Documents下的文件消失可能会导致。故，此处将
     * 缓存用户信息放在Library下，针对6.1.0之前的已经登录用户需要把Documents下
     * 的登录缓存迁移到Library.
     */
//    NSString *oldCacheFilePath = [[NSFileManager defaultManager] pathForPublicFile:@"user.data"];
    NSString *cacheFilePath = [MFWUserInfo cachePathOfMyUserInfo];
//    if ([[NSFileManager defaultManager] fileExistsAtPath:oldCacheFilePath])
//    {
//        NSError *error = nil;
//        [[NSFileManager defaultManager] copyItemAtPath:oldCacheFilePath toPath:cacheFilePath error:&error];
//        
//        if (!error)
//        {
//            [[NSFileManager defaultManager] removeItemAtPath:oldCacheFilePath error:&error];
//        }
//    }
    
    
    NSData* data = [NSData dataWithContentsOfFile:cacheFilePath];
    MFWUserInfo* instance = nil;
    if (data)
    {
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        instance = [unarchiver decodeObject];
    }
    
    return instance;
}

#pragma mark - NSCoding methods
- (void)encodeWithCoder:(NSCoder *)aCoder;
{
    [aCoder encodeObject:_uid forKey:kCodingUid];
    [aCoder encodeObject:_nickName forKey:kCodingNikcName];
    [aCoder encodeObject:_logoUrl forKey:kCodingLogoUrl];
    [aCoder encodeInt:_level forKey:kCodingLevel];
    [aCoder encodeInt:_gender forKey:kCodingGender];
    [aCoder encodeObject:_ucity forKey:kCodingUCity];
    [aCoder encodeObject:_uIntro forKey:kCodingUIntro];
    [aCoder encodeObject:_m_bg_img forKey:kCodingUbgimg];
    [aCoder encodeInt:_un_read_chat_count forKey:kCodingUChatNum];
    [aCoder encodeObject:_email forKey:kCodingEmail];
    [aCoder encodeObject:_trueName forKey:kCodingTrueName];
    [aCoder encodeObject:_phone forKey:kCodingPhone];
    [aCoder encodeObject:_birthday forKey:kCodingBirthday];
    [aCoder encodeObject:_profile forKey:kCodingProfile];
    [aCoder encodeObject:_fans forKey:kCodingFans];
    [aCoder encodeObject:_concern forKey:kCodingConcern];
    [aCoder encodeObject:_sex forKey:kCodingSex];


}

- (id)initWithCoder:(NSCoder *)aDecoder;
{
    self = [super init];
    if (self)
    {
        _uid = [[aDecoder decodeObjectForKey:kCodingUid] copy];
        _nickName = [[aDecoder decodeObjectForKey:kCodingNikcName] copy];
        _logoUrl = [[aDecoder decodeObjectForKey:kCodingLogoUrl] copy];
        _level = [aDecoder decodeIntForKey:kCodingLevel];
        _gender = [aDecoder decodeIntForKey:kCodingGender];
        _ucity = [[aDecoder decodeObjectForKey:kCodingUCity] copy];
        _uIntro = [[aDecoder decodeObjectForKey:kCodingUIntro] copy];
        _m_bg_img = [[aDecoder decodeObjectForKey:kCodingUbgimg] copy];
        _un_read_chat_count = [aDecoder decodeIntegerForKey:kCodingUChatNum];
        _email = [[aDecoder decodeObjectForKey:kCodingEmail] copy];
       _phone = [[aDecoder decodeObjectForKey:kCodingPhone] copy];
        _trueName = [[aDecoder decodeObjectForKey:kCodingTrueName] copy];
        _birthday = [[aDecoder decodeObjectForKey:kCodingBirthday] copy];
        _profile = [[aDecoder decodeObjectForKey:kCodingProfile] copy];
        _fans = [[aDecoder decodeObjectForKey:kCodingFans] copy];
        _concern = [[aDecoder decodeObjectForKey:kCodingConcern] copy];
        _sex = [[aDecoder decodeObjectForKey:kCodingSex] copy];
    }
    return self;
}
@end
